<?php
namespace common\components\services;

use Yii;
use Exception;
use common\models\CdnConfig;

/**
 * Class CdnUpload
 * @package common\components\services
 */
class CdnUpload
{

    const ModuleName = 'cdn';

    /**
     * 初始化配置
     * initConfig
     * @param array $config
     * @return array
     */
    private static function initConfig($config = [])
    {
        $returnConfig['class'] = $config['class'];
        $returnConfig['host'] = $config['host'];

        if($config['class'] == CdnConfig::QiNiu){
            $returnConfig['accessKey'] = $config['accessKey'];
            $returnConfig['secretKey'] = $config['accessSecret'];
            $returnConfig['bucket'] = $config['bucket'];
        }else if($config['class'] == CdnConfig::QCloud){
            $returnConfig['appId'] = $config['appId'];
            $returnConfig['secretId'] = $config['accessKey'];
            $returnConfig['secretKey'] = $config['accessSecret'];
            $returnConfig['region'] = $config['bucket'];
        }else{
            $returnConfig['accessKey'] = $config['accessKey'];
            $returnConfig['accessSecret'] = $config['accessSecret'];
            $returnConfig['endPoint'] = $config['endPoint'];
            $returnConfig['bucket'] = $config['bucket'];
        }
        return $returnConfig;
    }

    /**
     * getTarget
     * @return object|null
     */
    public static function getTarget()
    {
        try {
            $cdnConfig = CdnConfig::findActive();
            if(empty($cdnConfig)){
                return null;
            }
            return Yii::createObject(self::initConfig($cdnConfig));
        }catch (Exception $e){
            exceptionFormat($e);
            Yii::error('Get Upload Target Module : '.self::ModuleName.' Fail');
            return null;
        }
    }
}